<template>
  <div>
    <Category :disabled="isAddShow" />
    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
      style="margin-top: 30px"
      v-show="!isAddShow"
    >
      <template #header>
        <el-button
          type="primary"
          size="default"
          icon="ele-Plus"
          @click="addAttr"
          :disabled="!category3Id"
          >添加属性</el-button
        >
      </template>
      <!-- card body -->
      <el-table :data="attrList" border stripe>
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column label="属性名称" prop="attrName"></el-table-column>
        <el-table-column
          label="属性值名称列表"
          width="500"
          prop="attrValueList"
        >
          <template v-slot="{ row }">
            <el-tag
              style="margin-right: 5px"
              type="danger"
              size="default"
              effect="dark"
              v-for="item in row.attrValueList"
              :key="item.id"
              >{{ item.valueName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              size="small"
              icon="ele-Edit"
              @click="updateAttr(row)"
            ></el-button>
            <!-- 气泡确认框 -->
            <el-popconfirm
              title="是否确认删除?"
              @confirm="confirmDelete(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  icon="ele-Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
      style="margin-top: 30px"
      v-show="isAddShow"
    >
      <el-form label-width="80px" :inline="true">
        <el-form-item label="属性名">
          <el-input v-model="newAttr.attrName" />
        </el-form-item>
      </el-form>
      <div>
        <el-button
          type="primary"
          size="default"
          @click="addAttrValue"
          :disabled="!newAttr.attrName"
          >添加属性值</el-button
        >
        <el-button type="default" size="default" @click="isAddShow = false"
          >取消</el-button
        >
      </div>
      <el-table
        :data="newAttr.attrValueList"
        border
        stripe
        style="margin: 20px 0"
      >
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column label="属性值名称">
          <template v-slot="{ row, $index }">
            <el-input
              v-if="row.isEdit"
              v-model="row.valueName"
              size="small"
              clearable
              @blur="toLook(row, $index)"
              ref="editEle"
            >
            </el-input>
            <p v-else @click="toEdit(row)">{{ row.valueName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ $index }">
            <el-button
              type="danger"
              size="samll"
              icon="ele-Delete"
              @click="delAttrValue($index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-button
          type="primary"
          size="default"
          @click="save"
          :disabled="!newAttr.attrName || newAttr.attrValueList.length === 0"
          >保存</el-button
        >
        <el-button type="default" size="default" @click="isAddShow = false"
          >取消</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Attr",
});
</script>

<script setup lang="ts">
import { watch, ref, nextTick ,onMounted } from "vue";
import { storeToRefs } from "pinia";
import {
  reqAttrInfoList,
  type attrListType,
  type attrValueItemType,
  type attrItemType,
  reqAddOrUpdateAttrList,
  reqDelAttr,
} from "@/api/attr";
import { ElMessage } from "element-plus";
import useCategoryStore from "@/stores/category";
import { cloneDeep } from "lodash";
const categoryStore = useCategoryStore();


// 获取三级分类的值
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore);
// 初始化一个属性列表的数据
const attrList = ref<attrListType>([]);

// 封装请求属性列表
const getAttrList = async () => {
  // 3Id改变,重新发送请求
  try {
    const result = await reqAttrInfoList(
      category1Id.value as number,
      category2Id.value as number,
      category3Id.value as number
    );

    // 对初始值进行赋值
    attrList.value = result;
  } catch (e: any) {
    ElMessage.error(e.message);
  }
};
// 三级分类的第三个id改变,初始化发送属性列表请求
watch(category3Id, async (newVal) => {
  if (!newVal) {
    attrList.value = [];
    return;
  }
  // 重新请求
  getAttrList();
});

// 组件切换三级联动进行清空
onMounted(() => {
  category1Id.value = null, 
  category2Id.value = null, 
  category3Id.value = null
})

// 声明一个值 控制新增属性和属性列表组件的切换
const isAddShow = ref(false);

// 收集新创建的属性
const newAttr = ref<attrItemType>({
  attrName: "",
  categoryId: category3Id.value as number,
  categoryLevel: 3,
  attrValueList: [],
});

const editEle = ref<HTMLInputElement>();
// 把创建的新的newAttrValue对象插入到newAttr的attrValueList的数组中
const addAttrValue = () => {
  const newAttrValue: attrValueItemType = {
    valueName: "",
    attrId: newAttr.value.id,
    isEdit: true, //新增一个属性,代表当前是编辑模式还是查看模式
  };
  newAttr.value.attrValueList.push(newAttrValue);
  nextTick(() => {
    editEle.value?.focus();
  });
};

// 当点击修改某个属性的时候 回调函数
const updateAttr = (row: attrItemType) => {
  isAddShow.value = true;
  newAttr.value = cloneDeep(row);
  newAttr.value.attrValueList.forEach((item) => {
    item.isEdit = false;
  });
};

// 添加属性
const addAttr = () => {
  isAddShow.value = true;
  newAttr.value = {
    attrName: "",
    categoryId: category3Id.value as number,
    categoryLevel: 3,
    attrValueList: [],
  };
};

//查看模式切换编辑模式事件回调函数
const toEdit = (row: attrValueItemType) => {
  row.isEdit = true;
  nextTick(() => {
    editEle.value?.focus();
  });
};

// 编辑模式切换至查看模式
const toLook = (row: attrValueItemType, index: number) => {
  // 如果为空则删除
  if (row.valueName === "") {
    newAttr.value.attrValueList.splice(index, 1);
  }
  // 如果相等也删除
  const isRow = newAttr.value.attrValueList.some((item) => {
    if (item !== row) {
      return item.valueName === row.valueName;
    }
  });
  if (isRow) {
    newAttr.value.attrValueList.splice(index, 1);
  }
  row.isEdit = false;
};

// 删除属性
const delAttrValue = (index: number) => {
  newAttr.value.attrValueList.splice(index, 1);
};

// 提交更新或者新增
const save = async () => {
  newAttr.value.attrValueList.forEach((item) => {
    // 清除内部isEdit属性
    delete item.isEdit;
  });
  if (!newAttr.value.attrName || newAttr.value.attrValueList.length === 0) {
    return ElMessage.error("属性名或属性值不能为空！");
  }
  try {
    if (newAttr.value.id) {
      await reqAddOrUpdateAttrList(newAttr.value);
      ElMessage.success("修改成功");
    } else {
      await reqAddOrUpdateAttrList(newAttr.value);
      ElMessage.success("添加成功");
    }
    //切换到属性列表
    isAddShow.value = false;
    // 重新请求
    getAttrList();
  } catch (e: any) {
    return ElMessage.error(e);
  }
};

// 气泡确认删除属性
const confirmDelete = async (id: number) => {
  try {
    await reqDelAttr(id);
    ElMessage.success("删除成功");
    // 重新请求
    getAttrList();
  } catch (e: any) {
    return ElMessage.error(e);
  }
};
</script>

<style scoped></style>
